import pandas as pd
import numpy as np
from scipy.stats import pearsonr
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression
import statsmodels.api as sm
import statsmodels.formula.api as smf
from sklearn.metrics import confusion_matrix, classification_report
import math
import random

# 假设我们有一个DataFrame df 包含了各个测试条目的分数
# 示例数据加载
df = pd.read_csv("data-final.csv")

# 计算Cronbach's Alpha
def cronbach_alpha(df):
    item_variances = df.var(axis=0, ddof=1)
    total_variance = df.sum(axis=1).var(ddof=1)
    n_items = df.shape[1]
    alpha = (n_items / (n_items - 1)) * (1 - (item_variances.sum() / total_variance))
    return alpha

# 示例：对某一人格维度的条目进行Cronbach's Alpha计算
extroversion_items = df[['EXT1', 'EXT2', 'EXT3', 'EXT4', 'EXT5', 'EXT6', 'EXT7', 'EXT8', 'EXT9', 'EXT10']]
alpha_extroversion = cronbach_alpha(extroversion_items)
print(f'Cronbach\'s Alpha for Extroversion: {alpha_extroversion}')
####################################################
#结构效度
from sklearn.decomposition import FactorAnalysis
import matplotlib.pyplot as plt

# 假设我们有一个DataFrame df 包含了所有测试条目的分数
# 示例数据加载
df = pd.read_csv("path_to_your_dataset.csv")

# 进行因子分析
fa = FactorAnalysis(n_components=5)
fa.fit(df)

# 查看因子负荷矩阵
loadings = pd.DataFrame(fa.components_.T, index=df.columns)
print(loadings)

# 绘制碎石图（Scree Plot）
evr = fa.explained_variance_ratio_
plt.plot(range(1, len(evr) + 1), evr, marker='o')
plt.xlabel('Number of Components')
plt.ylabel('Explained Variance Ratio')
plt.title('Scree Plot')
plt.show()
################################################
#效标效度
from scipy.stats import pearsonr

# 假设我们有一个效标变量criterion_variable
criterion_variable = df['criterion_variable']

# 计算相关系数
correlation, p_value = pearsonr(df['EXT1'], criterion_variable)
print(f'Correlation between EXT1 and Criterion: {correlation}, p-value: {p_value}')


